package kz.pompei.ifacer.dialogs;

import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

public class DiaUtil {
  public static Window extractWindow(Component parentComponent) {
    Component cur = parentComponent;
    while (cur != null && !(cur instanceof Window)) {
      cur = cur.getParent();
    }
    return (Window)cur;
  }
  
  public static void put(JDialog dia, String dialogName, Window parentWindow, int x0, int y0,
      int width0, int height0) {
    if (parentWindow == null) {
      dia.setBounds(x0, y0, width0, height0);
      return;
    }
    
    dia.setSize(dia.getContentPane().getPreferredSize());
    int x = parentWindow.getX() + parentWindow.getWidth() / 2 - dia.getWidth() / 2;
    int y = parentWindow.getY() + parentWindow.getHeight() / 2 - dia.getHeight() / 2;
    dia.setLocation(x, y);
  }

  public static void makeEscapeKey(final JDialog dia) {
    String closeKey = "com.spodding.tackline.dispatch:WINDOW_CLOSING";
    
    JRootPane root = dia.getRootPane();
    root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), closeKey);
    
    Action closeAction = new AbstractAction() {
      @Override
      public void actionPerformed(ActionEvent e) {
        dia.dispatchEvent(new WindowEvent(dia, WindowEvent.WINDOW_CLOSING));
      }
    };
    
    root.getActionMap().put(closeKey, closeAction);
  }
}
